<template>
  <div id="Teacher">
    <div class="mt-4">
      <el-input
        v-model="queryValue"
        placeholder="请输入查询值"
        class="input-with-select"
        style="float: left;width: 300px"
      >
        <template #prepend>
          <el-select v-model="selectValue" placeholder="请选择查询项" style="width: 140px">
            <el-option label="姓名" value="tname" />
            <el-option label="所属班级" value="classGuide" />
          </el-select>
        </template>
        <template #append>
          <el-button :icon="Search" @click="selectTeacher(selectValue, queryValue)"/>
        </template>
      </el-input>
    </div>
    <el-button plain type="primary" circle style="margin-left: 20px" @click="clickAllTeacher" >All</el-button>
    <el-button plain :icon="Plus" :round="true" style="float: right" @click="clickToAdd">添加教师</el-button>
    <el-table :data="teacherAllData" empty-text="未查询到数据！" table-layout="auto" >
      <el-table-column fixed prop="tname" label="姓名" />
      <el-table-column prop="sex" label="性别" >
        <template #default="scope">
          <el-tag
            :type="scope.row.sex === '男' ? '' : 'danger'"
            disable-transitions
          >
            {{ scope.row.sex }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isClassGuide" label="是否班主任" >
        <template #default="scope">
          <el-tag
            :type="scope.row.isClassGuide === 1 ? 'success' : 'info'"
            disable-transitions
          >
            {{ scope.row.isClassGuide === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="classname" label="所属班级" />
      <el-table-column prop="remark" label="备注" min-width="500px" />
      <el-table-column fixed="right" label="操作" header-align="center" width="210">
        <template #default="scope">
          <el-button plain type="primary" :icon="Edit" @click="clickToModify(scope.row)">修改</el-button>
          <el-divider direction="vertical" />
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon-color="#626AEF"
            title="你确定要删除吗？"
            @confirm="clickToDelete(scope.row)"
          >
            <template #reference>
              <el-button type="danger" plain :icon="Delete">删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      hide-on-single-page
      :page-sizes="[10]"
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      v-model="teacherDialogVisible"
      :title="teacherTitle"
      width="30%"
      :before-close="closeForm"
    >
      <el-form
        ref="teacherFormRef"
        :model="teacherForm"
        :rules="teacherRules"
        label-width="100px"
        style="overflow: hidden;padding-right: 50px;width: 60%;margin: 10px auto"
      >
        <el-form-item label="姓名:" prop="tname" >
          <el-input placeholder="请输入姓名" v-model.number="teacherForm.tname" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-radio-group v-model="teacherForm.sex">
            <el-radio label="男" />
            <el-radio label="女" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否班导" prop="isClassGuide">
          <el-radio-group v-model="teacherForm.isClassGuide">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="班级" prop="classId" >
          <el-select v-model="teacherForm.classId" class="m-2" placeholder="请选择班级">
            <el-option
              v-for="item in classGuideAll"
              :key="item.classid"
              :label="item.classname"
              :value="item.classid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息:" prop="remark">
          <el-input v-model="teacherForm.remark" maxlength="50" resize="none" :rows="3" show-word-limit placeholder="请输入备注信息" type="textarea" />
        </el-form-item>
        <el-form-item style="float: right">
          <el-button-group>
            <el-button type="success" @click="submitForm(teacherFormRef)">确认</el-button>
            <el-button type="info" @click="closeForm">取消</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {ref, unref} from "vue";
import {Search,Plus,Edit,Delete} from "@element-plus/icons-vue"
import axios from "axios";
import {ElNotification} from "element-plus";

export default {
  name: "TeacherSys",
  setup() {

    /*查询*/
    let queryValue = ref()
    let selectValue = ref()
    const selectTeacher = (s, q) => {
      if (s == null || q == null) {
        clickAllTeacher()
      } else {
        teacherMode.value = 2
        currentPage.value = 1
        getTeacherAll("/api/getTeacherSelect?pageNum=1&pageSize=10&selectValue="+s+"&queryValue="+q)
        console.log(s, q)
      }
    }
    const clickAllTeacher = () => {
      getTeacherAll("/api/getTeacherAll?pageNum=1&pageSize=10")
      teacherMode.value = 1
      currentPage.value = 1
      queryValue.value = ""
      selectValue.value = ""
    }

    /*表格*/
    let teacherAllData = ref()
    const clickToModify = (data) => {
      teacherForm.value = JSON.parse(JSON.stringify(data))
      getClassName()
      teacherTitle.value = "修改教师信息"
      teacherDialogVisible.value = true
    }
    const clickToDelete = (data) => {
      axios.post("/api/deleteTeacher", data, {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then(res => {
        if (res.data.code === 200) {
          ElNotification({
            title: '成功',
            message: res.data.msg,
            type: 'success',
            offset: 100,
          })
        } else {
          ElNotification({
            title: '错误',
            message: res.data.msg,
            type: 'error',
            offset: 100,
          })
        }
        teacherMode.value = 1
        currentPage.value = 1
        clickAllTeacher()
      })
    }

    /*弹出对话框*/
    let teacherDialogVisible = ref(false)

    /*分页*/
    let total = ref(0)
    let currentPage = ref(1)
    let teacherMode = ref(1)  // 1:全部，2:查询
    const handleCurrentChange = (val) => {
      currentPage.value = val
      if (teacherMode.value === 1) {
        getTeacherAll("/api/getTeacherAll?pageNum="+val+"&pageSize=10")
      } else if (teacherMode.value === 2) {
        getTeacherAll("/api/getTeacherSelect?pageNum="+val+"&pageSize=10&selectValue="+selectValue.value+"&queryValue="+queryValue.value)
      }
    }

    /*添加 and 修改*/
    let teacherTitle = ref("添加教师")
    let teacherFormRef = ref()
    let teacherForm = ref({
      tname:'',
      sex: '',
      isClassGuide: '',
      classId: '',
      remark: ''
    })
    let teacherRules = ref()
    let classGuideAll = ref()
    const submitForm = (formEl) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          if (teacherTitle.value === "添加教师") {
            axios.post("/api/addTeacher", teacherForm.value, {
              headers: {
                token: localStorage.getItem("token")
              }
            }).then(res => {
              if (res.data.code === 200) {
                ElNotification({
                  title: '成功',
                  message: res.data.msg,
                  type: 'success',
                  offset: 100,
                })
              } else {
                ElNotification({
                  title: '错误',
                  message: res.data.msg,
                  type: 'error',
                  offset: 100,
                })
              }
              teacherMode.value = 1
              currentPage.value = 1
              clickAllTeacher()
            })
          } else if (teacherTitle.value === "修改教师信息") {
            axios.post("/api/updateTeacher", teacherForm.value, {
              headers: {
                token: localStorage.getItem("token")
              }
            }).then(res => {
              if (res.data.code === 200) {
                ElNotification({
                  title: '成功',
                  message: res.data.msg,
                  type: 'success',
                  offset: 100,
                })
              } else {
                ElNotification({
                  title: '错误',
                  message: res.data.msg,
                  type: 'error',
                  offset: 100,
                })
              }
              teacherMode.value = 1
              currentPage.value = 1
              clickAllTeacher()
            })
          }
          teacherDialogVisible.value = false
          unref(teacherFormRef).resetFields()
          teacherForm.value = {}
        } else {
          console.log("error")
        }
      })

    }
    const closeForm = () => {
      unref(teacherFormRef).resetFields()
      teacherForm.value = {}
      teacherDialogVisible.value = false
    }
    const clickToAdd = () => {
      teacherTitle.value = "添加教师"
      getClassName()
      teacherDialogVisible.value = true
    }

    /*数据*/

    getTeacherAll("/api/getTeacherAll?pageNum=1&pageSize=10")

    function getTeacherAll(url) {
      axios.get(url, {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then(res => {
        if (res.data.code === 200) {
          teacherAllData.value = res.data.data.teacherList
          total.value = res.data.data.total
        } else {
          ElNotification({
            title: '错误',
            message: res.data.msg,
            type: 'error',
            offset: 100,
          })
          teacherAllData.value = []
          total.value = 0
        }
      })
    }
    const getClassName = () => {
      axios.get("/api/classNameAll").then(res=>{
        classGuideAll.value = res.data.data
      })
    }
    teacherRules.value = {
      tname: [
        { required: true, trigger: 'blur', validator: checkTname },
      ],
      sex: [
        { required: true, trigger: 'blur', validator: checkSax },
      ],
      isClassGuide: [
        { required: true, trigger: 'blur', validator: checkIsClassGuide },
      ],
      classId: [
        { required: true, trigger: 'blur', validator: checkClassGuide },
      ],
    }

    function checkTname(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入姓名！！'));
      } else {
        callback()
      }
    }
    function checkSax(rule, value, callback) {
      if (!value) {
        return callback(new Error('请选择性别！！'));
      } else {
        callback()
      }
    }
    function checkIsClassGuide(rule, value, callback) {
      if (!value) {
        return callback(new Error('请选择是否班导！！'));
      } else {
        callback()
      }
    }
    function checkClassGuide(rule, value, callback) {
      if (!value) {
        return callback(new Error('请选择班级！！'));
      } else {
        callback()
      }
    }

    return {
      /*查询*/
      queryValue,
      selectValue,
      selectTeacher,
      clickAllTeacher,
      /*表格*/
      teacherAllData,
      clickToModify,
      clickToDelete,
      /*弹出对话框*/
      teacherDialogVisible,
      /*分页*/
      total,
      currentPage,
      handleCurrentChange,
      /*添加*/
      teacherTitle,
      teacherFormRef,
      teacherForm,
      teacherRules,
      classGuideAll,
      clickToAdd,
      submitForm,
      closeForm,
      /*icon图标*/
      Search,
      Plus,
      Edit,
      Delete
    }
  }
}
</script>

<style scoped>
#Teacher {
  margin: 50px auto;
  width: 50%;
  min-width: 1000px;
}
.el-pagination {
  float: right;
  margin: 50px auto;
}
</style>